package com.api_gateway.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/gateway")
public class GatewayStatusController {
    
    @Autowired(required = false)
    private RouteLocator routeLocator;
    
    @Autowired
    private DiscoveryClient discoveryClient;
    
    @GetMapping("/status")
    public Map<String, Object> getGatewayStatus() {
        Map<String, Object> status = new HashMap<>();
        
        // 检查路由数量
        if (routeLocator != null) {
            long routeCount = routeLocator.getRoutes().count().block();
            status.put("routeCount", routeCount);
            status.put("routesAvailable", routeCount > 0);
        } else {
            status.put("routeCount", 0);
            status.put("routesAvailable", false);
            status.put("routeLocatorError", "RouteLocator is null - Gateway可能未正确配置");
        }
        
        // 检查服务发现
        List<String> services = discoveryClient.getServices();
        status.put("discoveredServices", services);
        status.put("serviceCount", services.size());
        
        // 检查网关组件
        status.put("gatewayEnabled", isGatewayEnabled());
        status.put("timestamp", System.currentTimeMillis());
        
        return status;
    }
    
    private boolean isGatewayEnabled() {
        try {
            Class.forName("org.springframework.cloud.gateway.config.GatewayAutoConfiguration");
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }
    }
}